﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="sv-se" lang="sv-se">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<link rel="stylesheet" href="StyleSheet.css" type="text/css"/>
   
	<title>Klotterplanket</title>
</head>
<body>

	<h1>Klotterplanket</h1>
	<form action="klotterplanket.php" method="post">
		<p><label for="scribbler">Klottrare:<input type="text" name="scribbler" id="scribbler"/></label></p>
		
		<p><label for="scribble">Klotter:</label></p>
		<p><textarea name="scribble" id="scribble" cols="50" rows="10"></textarea></p>
		    
		<h3><input type="submit" value="Klottra!" /></h3>
	</form>
	<h2>Allt klotter</h2>
	<?php
		$newScribble = FormPostToScribble::create();
		ScribbleRepository::add($newScribble);
	
		$scribbles = ScribbleRepository::getAll();
		
		foreach ($scribbles as $scribble) {
			echo "<span class='scribbler'>".$scribble->scribbler."</span><span class='timeStamp'>".$scribble->timeStamp."</span><br/>";
			echo "<span class='text'>".$scribble->text."</span><br/><br/>";
		}
	?><br />

</body>
</html>

<?php
class ScribbleRepository
{
    public static function add($scribble) {
		$conn = mysql_connect("localhost", "malro956", "malro956e290");
		mysql_select_db("malro956", $conn);
		
		$scribblerParam = htmlspecialchars(mysql_real_escape_string(trim($scribble->scribbler)));
		$textParam = htmlspecialchars(mysql_real_escape_string(trim($scribble->text)));
		
		if ($scribblerParam == "" || $textParam == "") {
			echo '<div class="errorMsg">Fel! Klottrare och klotter måste anges!</div>';
		}
		else {
		
		$sql = "INSERT INTO Scribble (Scribbler, Text) VALUES ('".$scribblerParam."', '".$textParam."')";
		
		mysql_query($sql);
		
		mysql_close($conn);
    }
	}
	
	public static function getAll() {
		$conn = mysql_connect("localhost", "malro956", "malro956e290");
		mysql_select_db("malro956", $conn);
		
		$dbScribbles = mysql_query("SELECT Scribbler, Text, TimeStamp FROM Scribble ORDER BY TimeStamp DESC");
		$scribbles = array();
		
		while($row = mysql_fetch_object($dbScribbles))
		{
			$scribble = new ScribbleWithTimeStamp();
			$scribble->scribbler = $row->Scribbler;
			$scribble->text = $row->Text;
			$scribble->timeStamp = $row->TimeStamp;
			
			array_push($scribbles, $scribble);
		}
		
		mysql_close($conn);
		
		return $scribbles;
	}
}

class Scribble
{
	public $scribbler;
	public $text;
}

class ScribbleWithTimeStamp extends Scribble
{
	public $timeStamp;
}

class FormPostToScribble
{
	public static function create() {
		$scribble = new Scribble();
		$scribble->scribbler = $_POST["scribbler"];
		$scribble->text = $_POST["scribble"];
		
		return $scribble;
	}
}
?>